<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
/**
 * 2020-02-08
 * 这是从rakuten获取数据判断每天接口新数据
 */
class Rakuten extends Command
{
    protected $signature = 'rakuten';
    protected $description = 'rakuten数据源判断每天新进的卡券数量';
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('*********************program start***********************');
        
        /**获取token */
        $token_url=[
            'https://api.rakutenmarketing.com/token?grant_type=password&username=msboperation&password=domenic7adr7&scope=1625937',
            'https://api.rakutenmarketing.com/token?grant_type=password&username=msboperation&password=domenic7adr7&scope=1554277'
        ];

        $client=new Client();
        //发送异步并发请求 获取数据
        $req_param=[
            'headers'=>[
                'Authorization'=>'Basic ZklSZ2U2dW1KQ19aYnlPM1NKRjVrSlg4OThnYTowR2g3VXYyNDVyWHd2clY3YmVVb1hrS1R5VUFh',
                'Content-Type'=>'application/x-www-form-urlencoded'
            ]
        ];
        $promises=[
            'token1'=>$client->requestAsync('POST',$token_url[0],$req_param),
            'token2'=>$client->requestAsync('POST',$token_url[1],$req_param)
        ];
        $res_token = Promise\unwrap($promises);
        $this->line('Running:'.'获取token成功'.time());

        $token_array=[]; //存储获取到的token
        $token_array[]=json_decode($res_token['token1']->getBody()->read(100000000),true)['access_token'];
        $token_array[]=json_decode($res_token['token2']->getBody()->read(100000000),true)['access_token'];
        
        /**根据请求到的token 获取接口数据*/
        $total_url='https://api.rakutenmarketing.com/coupon/1.0?resultsperpage=500&pagenumber=';
        $promises2=[
            'total1'=>$client->requestAsync('GET',$total_url.'1',['headers'=>['Authorization'=>'Bearer '.$token_array[0]],'verify' => false]),
            'total2'=>$client->requestAsync('GET',$total_url.'1',['headers'=>['Authorization'=>'Bearer '.$token_array[1]],'verify' => false]),
        ];
        $res_total = Promise\unwrap($promises2);

        $pagecount1=(int)simplexml_load_string($res_total['total1']->getBody()->read(100000000))->TotalPages;
        $pagecount2=(int)simplexml_load_string($res_total['total2']->getBody()->read(100000000))->TotalPages;
        $this->line('Running:'.'获取总页数成功'.time());
        
        /**根据页数数据拼装请求 获取数据 */
        $promises3=[];
        for ($i=1; $i <= $pagecount1; $i++) { 
            $promises3['a'.$i]=$client->requestAsync('GET',$total_url.$i,['headers'=>['Authorization'=>'Bearer '.$token_array[0]],'verify' => false,'http_errors' => false]);
            // $res_total_data['a'.$i]=$client->request('GET',$total_url.$i,['headers'=>['Authorization'=>'Bearer '.$token_array[0]]]);
            $this->line('Running:...');
        }
        
        for ($i=1; $i <= $pagecount2; $i++) { 
            $promises3['b'.$i]=$client->requestAsync('GET',$total_url.$i,['headers'=>['Authorization'=>'Bearer '.$token_array[1]],'verify' => false,'http_errors' => false]);
            // $res_total_data['b'.$i]=$client->request('GET',$total_url.$i,['headers'=>['Authorization'=>'Bearer '.$token_array[1]]]);
            $this->line('Running:...');
        
        }

        $res_total_data = Promise\unwrap($promises3);
        $this->line('Running:'.'请求总数据成功'.time());

        //查询出数据库中已经存在的数据id
        $manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");

        //查库参数
        $filter = [];
        $options = [
            'projection' => [
                'clickurl' => 1,
                '_id'=>0
            ]
        ];

        // 查询数据库中数据
        $query = new \MongoDB\Driver\Query($filter, $options);
        $cursor = $manager->executeQuery('local.rakuten', $query);
        
        $urls=[];
        foreach ($cursor as $key => $value) {
            $value=(array)$value;
            $urls[]=$value['clickurl'];
        }
        
        for ($i=1; $i <= $pagecount1; $i++) { 
            $tosave_data=$res_total_data['a'.$i]->getBody()->read(100000000);
            
            //判断接口是否禁止访问，禁止访问则一分钟后再继续进行操作
            if(strstr($tosave_data,'fault') || strstr($tosave_data,'fault')){

                $this->line('error:'.$i);
                continue;
                $this->line('Running:接口错误'.'a'.$i);
                for ($j=1; $j < 62; $j++) { 
                    $this->line('Running:[接口错误]会在'.$j.'s后重新请求，共60s');
                    sleep(1);
                }
                $client->request('GET',$total_url.$i,['headers'=>['Authorization'=>'Bearer '.$token_array[0]],'verify' => false,'http_errors' => false]);
                $tosave_data=$res_total_data['a'.$i]->getBody()->read(100000000);
                $this->line('Running:接口正常访问');
            }
            $tosave_xml_data=simplexml_load_string($tosave_data);
            $coupons=$tosave_xml_data->link;
            
            //对接口中获取的coupon数据进行
            $to_save_coupons=[];
            foreach ($coupons as $key => $value) {
                $value=(array)$value;
                if(!in_array($value['clickurl'],$urls)){
                    $to_save_coupons[]=[
                        'offerdescription'=>$value['offerdescription'],
                        'offerenddate'=>$value['offerenddate'],
                        'clickurl'=>$value['clickurl'],
                        'create_time'=>date('Y-m-d')
                    ];
                }
            }
            //将数据保存到mongodb中
            if($to_save_coupons){
                $bulk = new \MongoDB\Driver\BulkWrite;

                foreach ($to_save_coupons as $key => $value) {
                    $bulk->insert($value); 
                }
                $result=$manager->executeBulkWrite('local.rakuten', $bulk);
                $this->line('save new data');
            }else{
                $this->line('same data is out');
            }

        }

        for ($i=1; $i <= $pagecount2; $i++) { 
            $tosave_data=$res_total_data['b'.$i]->getBody()->read(100000000);
            $tosave_xml_data=simplexml_load_string($tosave_data);
            $coupons=$tosave_xml_data->link;
            
            //对接口中获取的coupon数据进行
            $to_save_coupons=[];
            foreach ($coupons as $key => $value) {
                $value=(array)$value;
                if(!in_array($value['clickurl'],$urls)){
                    $to_save_coupons[]=[
                        'offerdescription'=>$value['offerdescription'],
                        'offerenddate'=>$value['offerenddate'],
                        'clickurl'=>$value['clickurl'],
                        'create_time'=>date('Y-m-d')
                    ];
                }
            }
            //将数据保存到mongodb中
            if($to_save_coupons){
                $bulk = new \MongoDB\Driver\BulkWrite;

                foreach ($to_save_coupons as $key => $value) {
                    $bulk->insert($value); 
                }
                $result=$manager->executeBulkWrite('local.rakuten', $bulk);
                $this->line('save new data');
            }else{
                $this->line('same data is out');
            }

        }
        $this->info('**********************program stop***********************');
    }
    
}
